package com.example.finalassessment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.finalassessment.model.Product;
import com.example.finalassessment.model.User;
import com.example.finalassessment.dao.UserMapper;
import com.example.finalassessment.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.finalassessment.util.ExceptionCodeMsgEnum;
import com.example.finalassessment.util.JwtHelper;
import com.example.finalassessment.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author funny_chao
 * @since 2024-12-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired//token
    private JwtHelper jwtHelper;

    @Override
    public boolean doRegister(User user) {
        System.out.println("接收到的用户名: " + user.getUsername());
        // 检查用户名是否已经存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User user1 = userMapper.selectOne(queryWrapper.eq("username", user.getUsername()));

        System.out.println("查询结果: " + user1);

        if (user1 != null) {
            System.out.println("已经存在");
            throw new RuntimeException(ExceptionCodeMsgEnum.USERNAME_ALREADY_EXISTS.getMessage());
        } else {
            userMapper.insert(user);
            System.out.println("注册成功");
            return true; // 注册成功

        }
    }

    @Override
    public String doLogin(User user) {
        System.out.println("接收到的用户名: " + user.getUsername());
        System.out.println("接收到的密码: " + user.getPassword());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User user1 = userMapper.selectOne(queryWrapper.eq("username", user.getUsername()));
        if (user1 == null) {
            throw new RuntimeException(ExceptionCodeMsgEnum.INVALID_USERNAME_OR_PASSWORD.getMessage());
        } else {
            if (!user1.getPassword().equals(user.getPassword())) {
                throw new RuntimeException(ExceptionCodeMsgEnum.INVALID_USERNAME_OR_PASSWORD.getMessage());
            } else {
                System.out.println("登录成功");

                // 生成token，确保传入Long类型的参数
                String token = jwtHelper.createToken(Long.valueOf(user1.getId()));
                return token;
            }
        }
    }

    @Override
    public User getById(Integer id) {
        User user = this.baseMapper.selectById(id); // 使用 baseMapper 来查询数据库
        if (user == null) {
            return null;
        }
        return user;
    }

    @Override
    public ResponseData editUser(Integer id, User user) {
        User updatedUser = userMapper.selectById(id);
        if (updatedUser == null) {
            return ResponseData.error(ExceptionCodeMsgEnum.PRODUCT_NOT_FOUND);
        }

        // 更新商品字段
        updatedUser.setUsername(user.getUsername());
        updatedUser.setEmail(user.getEmail());
        updatedUser.setPassword(user.getPassword());
        updatedUser.setPhone(user.getPhone());
        updatedUser.setGender(user.getGender());

        // 执行更新操作
        int rows = userMapper.updateById(updatedUser);
        if (rows > 0) {
            return ResponseData.success(updatedUser); // 返回更新后的商品数据
        } else {
            return ResponseData.error(ExceptionCodeMsgEnum.UPDATE_FAILED);
        }
    }

    @Override
    public ResponseData deleteUser(Integer id) {
        boolean isDeleted = this.removeById(id);

        if (!isDeleted) {
            // 删除失败，返回错误响应
            return ResponseData.error(ExceptionCodeMsgEnum.DELETE_FAILED);
        }

        // 删除成功，返回成功响应
        return ResponseData.success("删除成功", null);
    }

    @Override
    public ResponseData addUser(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User existingUser = userMapper.selectOne(queryWrapper.eq("username", user.getUsername()));
        if (existingUser != null) {
            return ResponseData.error(ExceptionCodeMsgEnum.PRODUCT_ALREADY_EXISTS);
        }
        // 添加商品
        int rows = userMapper.insert(user);
        if (rows > 0) {
            return ResponseData.success("商品添加成功", user);
        } else {
            return ResponseData.error(ExceptionCodeMsgEnum.ADD_FAILED);
        }
    }

    @Override
    public ResponseData getUserCountPerDay() {
        try {
            // 执行 SQL 查询，按天统计用户数量
            List<Map<String, Object>> result = userMapper.selectMaps(new QueryWrapper<User>()
                    .select("DATE(created_at) as date", "COUNT(*) as user_count")
                    .groupBy("DATE(created_at)")
                    .orderByAsc("DATE(created_at)"));

            // 如果查询到数据，则返回成功响应
            if (result != null && !result.isEmpty()) {
                return ResponseData.success(result);
            } else {
                return ResponseData.error(ExceptionCodeMsgEnum.CONTENT_NOT_EXIST);
            }
        } catch (Exception e) {
            return ResponseData.error(ExceptionCodeMsgEnum.SERVER_ERROR);
        }
    }
    @Override
    public ResponseData updateUser(User user) {
        // 使用 MyBatis-Plus 更新用户信息
        int rows = userMapper.updateById(user);
        if (rows > 0) {
            return ResponseData.success("信息更新成功", user);
        } else {
            return ResponseData.error(ExceptionCodeMsgEnum.UPDATE_FAILED);
        }
    }


}
